package com.openxt.nbzj.remoting;

import android.os.AsyncTask;

import com.alibaba.fastjson.JSONObject;

public class BusinessExTask extends AsyncTask<JSONObject, Integer, JSONObject> {
	private RemotingEx callBack = null;
	private ClientEx client = null;

	public BusinessExTask(RemotingEx callBack) {
		this.callBack = callBack;
	}

	public boolean cancelTask() {
		if (cancel(true)) {
			this.callBack = null;
			return true;
		}
		return false;
	}

	protected JSONObject doInBackground(JSONObject... params) {
		try {
			JSONObject packet = params[0];
			client = (ClientEx) packet.get("client");
			if (packet != null && client != null) {
				String result = client.request(packet.get("args"));
				if (result == null)
					throw new Exception("返回数据错误");

				JSONObject json = new JSONObject();
				json.put("status", ClientEx.STATUS_OK);
				json.put("value", result);
				return json;
			}
		} catch (Exception e) {
			try {
				JSONObject json = new JSONObject();
				json.put("status", ClientEx.STATUS_ERR);
				json.put(ClientEx.ERR_MESSAGE, e.getMessage());
				return json;
			} catch (Exception e0) {
			}
		}

		JSONObject json = new JSONObject();
		try {
			json.put("status", ClientEx.STATUS_ERR);
			json.put("message", "尚不支持该服务");
		} catch (Exception e0) {
		}
		return json;
	}

	protected void onPostExecute(JSONObject result) {
		super.onPostExecute(result);
		
		if (!ClientEx.STATUS_OK.equals(result.getString("status")) && this.callBack != null)
			this.callBack.onError(result.getString("message"));
		else if (this.callBack != null)
			this.callBack.onSuccess(result.getString("value"));
	}
}